// dllmain.cpp : Defines the entry point for the DLL application.

#include <process.h>
#include "utils.h"
#include "addlog.h"
#include "codecaves.h"
#include "servercontrol.h"
#include "player_info.h"

void (*iPrint)(int r,const char *text,...) = (void(*)(int,const char*,...))0x004b3800;
void ( __cdecl *ExecuteCommand)(const char *cmd) = ( void(__cdecl*)(const char*) ) 0x0047EA20;

ServerControl* server = NULL;
PlayerManager* manager = NULL;
void App_Initialize(void* param)
{
	static bool runonce = false;
	if(runonce)
		return;
	runonce = true;
	// Wait a while before starting up
	//Sleep(75000);
	add_log("initializing superapp...");
	//ExecuteCommand("sv_say \"Hey, superapp loaded\"");
	//return;
	//InitAddLog(hModule);
	CodecaveCheckCmd();
	CodecaveChatCmd();
	//return;
	// Disabled for release #1
	//CodecavePlayerScoreEvents();
	if(!server)
	{
		iPrint(0, "init: server");
		server = new ServerControl;//PLAYERADDY, OBJECTADDY, ALTERADDY, MACHINEADDY);
	}
	if(!manager && server)
	{
		iPrint(0, "init: manager");
		manager = new PlayerManager;
	}
	SetServer(server);
	SetManager(manager);
	// Disabled for release #1, but still required to initialize the Manager. (It doesnt go on to inf-loop though)
	_beginthread(PlayerWatcher, NULL, NULL);

	add_log("Initialized superapp");

}

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
					 )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		InitAddLog(hModule);
		add_log("loading dll\n");
		_beginthread( App_Initialize, NULL, NULL);
		return true;
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
		break;
	case DLL_PROCESS_DETACH:
		ExitAddLog();
		if(manager){
			manager->SavePlayers();
			manager->teleport.Save();
		}
		//iPrint(0, "bye");
		// A: restore where the codecave occured.
		//ExitAddLog();
		//delete Server();
		//delete Manager();
		//char oldcmd[5] = {0x57, 0xFF, 0xD0, 0x85, 0xC0};
		//WriteBytes((void*)0x0054C4BA, oldcmd, 5);
		break;
	}
	return true;
}

